import xbmc
import xbmcplugin
import xbmcaddon
import xbmcgui

import urllib
import urllib2
import re
import sys
import os
import time
import socket
from StringIO import StringIO
import gzip

import json
import hashlib


from sqlite3 import dbapi2 as sqlite

__addon_id__ = 'plugin.browser.undermedia'
__addon__ = xbmcaddon.Addon(id=__addon_id__)
__addonversion__ = __addon__.getAddonInfo('version')
__addonname__ = __addon__.getAddonInfo('name')


UMTVUSERNAME = __addon__.getSetting("username")
UMTVPASSWORD = __addon__.getSetting("password")
UMTVPROTO = __addon__.getSetting("proto")
UMTVURL = __addon__.getSetting("url")
UMTVPORT = __addon__.getSetting("port")
ASKFORTRAILERVIEW = __addon__.getSetting("ask_for_trailers")
passmd5 = hashlib.md5()
passmd5.update(UMTVPASSWORD)
HPASSWORD = passmd5.hexdigest();
APIURL = UMTVPROTO + '://' + UMTVURL + ':' + UMTVPORT

USERAGENT = u"Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1"

VIDEODB = os.path.join(xbmc.translatePath("special://database"), 'MyVideos75.db')
LOCALVIDEOPATH = os.path.join(xbmc.translatePath("special://home"), 'umediatv')
SOURCESXMLDATAPATH = os.path.join(xbmc.translatePath("special://userdata"), "sources.xml")

# url = 'https://72.249.8.165:9875?user='+USERNAME+'&key='+passmd5.hexdigest()
from xbmcswift2 import Plugin, ListItem

plugin = Plugin(__addonname__, __addon_id__, __file__, 'video')


# Write something on XBMC log
def getMovies():
    ensureDir(LOCALVIDEOPATH)
    msg = 'Updating Library...'
    title = 'Undermedia.TV'
    delay = 5000
    image = ''
    xbmc.executebuiltin('XBMC.Notification("%s", "%s", "%s", "%s")' % (msg, title, delay, image))
    _movies = getUrlData(APIURL + '/?' + urllib.urlencode({'user' : UMTVUSERNAME, 'secret' : HPASSWORD }))
    for movie in _movies['movies']:
        _srmdata = getUrlData(APIURL + movie['strm'] + '&' + urllib.urlencode({'user' : UMTVUSERNAME, 'secret' : HPASSWORD }))
        localFile = open(LOCALVIDEOPATH + '/' + movie['name'] + '.strm', 'w')
        localFile.write(_srmdata.encode('utf-8').strip())
        localFile.close()
        _nfodata = getUrlData(APIURL + movie['nfo'] + '&' + urllib.urlencode({'user' : UMTVUSERNAME, 'secret' : HPASSWORD }))
        localFile = open(LOCALVIDEOPATH + '/' + movie['name'] + '.nfo', 'w')
        localFile.write(_nfodata.encode('utf-8').strip())
        localFile.close()

def getUrlData(url):
    xbmc.log(url)
    response = urllib2.urlopen(url) 
    jsondata = json.load(response)
    if jsondata['request']['result'] == 'ok':
        return jsondata['request']['data']
    elif jsondata['request']['result'] == 'expiredaccount':
        xbmcgui.Dialog().ok("Expired Account", "Your account its not valid anymore")
    elif jsondata['request']['result'] == 'badcredentials':
        xbmcgui.Dialog().ok("Invalid login", "Wrong username or password")
    else:
        xbmcgui.Dialog().ok("Addon Error", "Please call for assistance")

def getRawUrlData(url):
    response = urllib2.urlopen(url)
    return response.read()

def ensureDir(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)
        

def cleanLibrary():
    data = xbmc.executeJSONRPC('{"jsonrpc":"2.0", "method":"VideoLibrary.Clean","id":1} ')
    print data
    
def scanLibrary():
    plugin.log.info('Scanning path ' + LOCALVIDEOPATH);
    data = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.Scan", "id": 1}')
    print data
    
def checkRequirements():
    '''
    Check undermedia requirements
    '''
    videopathok = False

    vdbc = sqlite.connect(VIDEODB)
    for row in vdbc.execute("SELECT strPath FROM path "):
        print '----' + row[0] + ' = ' + LOCALVIDEOPATH + '/----'
        if row[0] == LOCALVIDEOPATH + '/':
            videopathok = True

    if videopathok == False:
        print 'Tryng to insert'
        vdbc.execute("INSERT INTO path ( strPath, strContent, strScraper, noUpdate, exclude, scanRecursive, strSettings, useFolderNames ) VALUES ( '%s/', 'movies', 'metadata.themoviedb.org', 0,0, 2147483647, '<settings><setting id=\"RatingS\" value=\"TMDb\" /><setting id=\"TrailerQ\" value=\"No\" /><setting id=\"certprefix\" value=\"Rated \" /><setting id=\"fanart\" value=\"true\" /><setting id=\"keeporiginaltitle\" value=\"false\" /><setting id=\"language\" value=\"en\" /><setting id=\"tmdbcertcountry\" value=\"us\" /><setting id=\"trailer\" value=\"true\" /></settings>', 0 ) " % LOCALVIDEOPATH)
        vdbc.commit()

    print 'Checking file ' + SOURCESXMLDATAPATH
    touch(SOURCESXMLDATAPATH);
    sourcesdata = ''
    if os.path.isfile(SOURCESXMLDATAPATH):
        f = open (SOURCESXMLDATAPATH, "r")
        sourcesdata = f.read()
        
    checkSrcXml = getUrlData(APIURL + '/checksources?' + urllib.urlencode({'user' : UMTVUSERNAME, 'secret' : HPASSWORD, 'content' : sourcesdata, 'path' : LOCALVIDEOPATH + '/' }))
    f.close()
    if checkSrcXml['action'] == 'replace':
        localFile = open(SOURCESXMLDATAPATH, 'w')
        localFile.write(checkSrcXml['content'].encode('utf-8').strip())
        localFile.close()

def sync_message(msg, upgrade):
    # Don't show while watching a video
    while(xbmc.Player().isPlayingVideo() and not xbmc.abortRequested):
        xbmc.sleep(1000)
    i = 0
    while(i < 5 and not xbmc.abortRequested):
        xbmc.sleep(1000)
        i += 1
    # Detect if it's first run and only show OK dialog + ask to disable on that
    firstrun = __addon__.getSetting("versioncheck_firstrun") != 'false'
    if firstrun and not xbmc.abortRequested:
        xbmcgui.Dialog().ok(__addonname__,
                            __localize__(msg),
                            __localize__(32001),
                            __localize__(32002))
        # sets check to false which is checked on startup
        if dialog_yesno(32009, 32010):
            __addon__.setSetting("versioncheck_enable", 'false')
        # set first run to false to only show a popup next startup / every two days
        __addon__.setSetting("versioncheck_firstrun", 'false')
    # Show notification after firstrun
    elif not xbmc.abortRequested:
        if upgrade:
            return dialog_yesno(msg)
        else:
            xbmc.executebuiltin("XBMC.Notification(%s, %s, %d, %s)" % (__addonname__, __localize__(32001) + '' + __localize__(32002), 15000, __icon__))
    else:
        pass

def touch(fname, times=None):
    fhandle = file(fname, 'a')
    try:
        os.utime(fname, times)
    finally:
        fhandle.close()


def fetchPage(params={}):
    get = params.get
    link = get("link")
    ret_obj = {}
    if get("post_data"):
        plugin.log.info("called for : " + repr(params['link']))
    else:
        plugin.log.info("called for : " + repr(params))

    if not link or int(get("error", "0")) > 2:
        plugin.log.info("giving up")
        ret_obj["status"] = 500
        return ret_obj

    if get("post_data"):
        if get("hide_post_data"):
            plugin.log.info("Posting data", 2)
        else:
            plugin.log.info("Posting data: " + urllib.urlencode(get("post_data")), 2)

        request = urllib2.Request(link, urllib.urlencode(get("post_data")))
        request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    else:
        plugin.log.info("Got request")
        request = urllib2.Request(link)

    if get("headers"):
        for head in get("headers"):
            request.add_header(head[0], head[1])

    request.add_header('User-Agent', USERAGENT)

    if get("cookie"):
        request.add_header('Cookie', get("cookie"))

    if get("refering"):
        request.add_header('Referer', get("refering"))

    try:
        plugin.log.info("connecting to server...")

        con = urllib2.urlopen(request)
        ret_obj["header"] = con.info()
        ret_obj["new_url"] = con.geturl()
        if con.info().has_key('Content-Disposition'):
            localName = con.info()['Content-Disposition'].split('filename=')[1]
            if localName[0] == '"' or localName[0] == "'":
                localName = localName[1:-1]
            ret_obj["filename"] = localName
        if get("no-content", "false") == u"false" or get("no-content", "false") == "false":
            inputdata = con.read()
            ret_obj["content"] = inputdata

        con.close()

        plugin.log.info("Done")
        ret_obj["status"] = 200
        return ret_obj

    except urllib2.HTTPError, e:
        err = str(e)
        plugin.log.info("HTTPError : " + err)
        plugin.log.info("HTTPError - Headers: " + str(e.headers) + " - Content: " + e.fp.read())

        params["error"] = str(int(get("error", "0")) + 1)
        ret = fetchPage(params)

        if not "content" in ret and e.fp:
            ret["content"] = e.fp.read()
            return ret

        ret_obj["status"] = 500
        return ret_obj

    except urllib2.URLError, e:
        err = str(e)
        plugin.log.info("URLError : " + err)

        time.sleep(3)
        params["error"] = str(int(get("error", "0")) + 1)
        ret_obj = fetchPage(params)
        return ret_obj
